<!--优惠配置管理新增（编辑）页面-->
<template>
  <div class="padding-lr-xl">
    <el-card>
      <div>
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-form-item label="选择条件："></el-form-item>

          <el-form-item label="国内仓库" prop="warehouseIds">
            <el-select
              v-model="formData.warehouseIds"
              multiple
              collapse-tags
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="(item, key) in initData.warehouseMap"
                :key="key"
                :label="item"
                :value="parseInt(key)"
              />
            </el-select>
            <el-button @click="selectAll">全选</el-button>
          </el-form-item>

          <el-form-item label="部门" prop="deptIds">
            <el-select
              v-model="formData.deptIds"
              filterable
              clearable
              multiple
              placeholder="请选择"
              style="width: 300px"
            >
              <el-option
                v-for="(item, value) in initData.deptMap"
                :key="value"
                :label="item"
                :value="parseInt(value)"
              />
            </el-select>
            <el-button @click="selectAllCustomerServiceDept">客服部</el-button>
            <el-button @click="selectAllSaleDept">销售部</el-button>
            <el-button @click="selectAllServiceAndSaleDept">客服及销售部</el-button>
            <el-button @click="selectAllDept">全选</el-button>
            <el-button @click="clearAllDept">全不选</el-button>
          </el-form-item>

          <el-form-item label="对内/外收费" prop="chargeTypes">
            <el-select
              v-model="formData.chargeTypes"
              placeholder="请选择"
              multiple
            >
              <el-option
                v-for="item in chargeTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="parseInt(item.value)">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="渠道类型" prop="channelTypeId">
            <el-select
              v-model="formData.channelTypeId"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="(item, value) in initData.channelTypeMap"
                :key="value"
                :label="item"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="入库渠道" prop="customerChannelIds">
            <el-select
              v-model="formData.customerChannelIds"
              filterable
              clearable
              multiple
              collapse-tags
              placeholder="请选择"
            >
              <el-option
                v-for="(item, value) in initData.customerChannelMap"
                :key="value"
                :label="item"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>

          <!--用于列表处筛选-->
          <el-form-item label="类型">
            <el-input v-model="formData.typeStr" :disabled="true" style="width: 210px"></el-input>
          </el-form-item>

          <el-form-item label="客户简称">
            <el-select
              v-model="formData.customerIds"
              :remote-method="searchCustomer"
              placeholder="请输入至少两个关键字"
              multiple
              collapse-tags
              clearable
              filterable
              remote
            >
              <el-option
                v-for="(item, key) in customerMap"
                :key="key"
                :label="item"
                :value="parseInt(key)">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="排除的客户">
            <el-select
              v-model="formData.excludeCustomerIds"
              :remote-method="searchExcludeCustomer"
              placeholder="请输入至少两个关键字"
              multiple
              collapse-tags
              clearable
              filterable
              remote
            >
              <el-option
                v-for="(item, key) in excludeCustomerMap"
                :key="key"
                :label="item"
                :value="parseInt(key)">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="排除的部门">
            <el-select
              v-model="formData.excludeDeptIds"
              filterable
              clearable
              multiple
              placeholder="请选择"
            >
              <el-option
                v-for="(item, value) in initData.deptMap"
                :key="value"
                :label="item"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="有效时间" prop="validDateRange">
            <el-date-picker
              v-model="formData.validDateRange"
              unlink-panels
              type="daterange"
              style="width: 250px"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>

          <el-form-item label="增删触发条件">
            <el-button icon="el-icon-circle-plus-outline" @click="addTriggerCondition"></el-button>
            <el-button icon="el-icon-remove-outline" @click="removeTriggerCondition"></el-button>
          </el-form-item>

          <div v-for="(item, index) in triggerConditions" :key="index">
            <el-form-item label="触发条件" :required="true">
              <el-row v-for="(subItem, subIndex) in item.expressionList" :key="subIndex" style="margin-bottom: 20px">
                <el-col :span="150">
                  <el-form-item prop="variableCodeId">
                    <el-select
                      v-model="triggerConditions[index].expressionList[subIndex].variableCodeId"
                      filterable
                      placeholder="请选择变量代码"
                      style="width: 400px;margin-right: 10px"
                    >
                      <el-option
                        v-for="(item, key) in initData.variableCodeMap"
                        :key="key"
                        :label="item"
                        :value="parseInt(key)"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="100">
                  <el-select
                    v-model="triggerConditions[index].expressionList[subIndex].compareFlag"
                    style="width: 80px;margin-right: 10px"
                  >
                    <el-option
                      v-for="item in compareOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-col>

                <el-col :span="100">
                  <el-form-item prop="compareValue">
                    <el-input v-model="triggerConditions[index].expressionList[subIndex].compareValue" style="width:100px"></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="100">
                  <el-button style="margin-left: 5px" icon="el-icon-circle-plus-outline" @click="addLine(index)"></el-button>
                  <el-button v-if="subIndex!=0" style="margin-left: 5px" icon="el-icon-remove-outline" @click="removeLine(index, subIndex)"></el-button>
                </el-col>

              </el-row>
            </el-form-item>
          </div>

          <el-form-item label="新增费用："></el-form-item>

          <!--选择费用名称，自动加载该费用下的所有阿米巴科目-->
          <el-form-item label="费用名称" prop="payNameId">
            <el-select
              v-model="formData.payNameId"
              filterable
              clearable
              @change="changeSelect"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in initData.payNameList"
                :key="item.id"
                :label="item.payNameCn"
                :value="parseInt(item.id)"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="阿米巴科目" prop="amoebaSubjectId">
            <el-select
              v-model="formData.amoebaSubjectId"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="(item, value) in initData.amoebaSubjectMap"
                :key="value"
                :label="item"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="单价调整" prop="priceStr">
            <el-input type="text" v-model="formData.priceStr" style="width: 400px"></el-input>
          </el-form-item>

          <el-form-item label="币种" prop="currency">
            <el-select
              v-model="formData.currency"
              filterable
              style="width: 100px"
            >
              <el-option
                v-for="(item, value) in initData.currencyMap"
                :key="value"
                :label="item"
                :value="value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="最低收费">
            <el-input type="number" v-model="formData.lowestFee" placeholder="请输入" style="width: 100px"></el-input>
          </el-form-item>

          <el-form-item label="最高收费">
            <el-input type="number" v-model="formData.highestFee" placeholder="请输入" style="width: 100px"></el-input>
          </el-form-item>

          <el-form-item label="数量" prop="numStr">
            <el-input type="text" v-model="formData.numStr" style="width: 400px"></el-input>
          </el-form-item>

          <el-form-item label="结算人" prop="settlementUserId">
            <el-select
              v-model="formData.settlementUserId"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="(item, value) in initData.userMap"
                :key="value"
                :label="item"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="费用备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入内容" style="width:430px"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submitForm('elForm')">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
  import { ajax } from "@/store/yg/common/utils";
  import { closeDialog } from "@/utils";

  export default {
    data() {
      return {
        initData: {},
        customerMap: {},
        excludeCustomerMap: {},
        //将触发条件单独提出来，放formData中结构太复杂
        triggerConditions: [],

        formData: {
          warehouseIds: [],
          userGroupIds: [],
          settlementUserId: null,
          remark: '',
          currency: 'RMB',
          priceStr: null,
          numStr: null,
          channelTypeId: null,
          customerChannelIds: [],
          amoebaSubjectId: null,
          payNameId: null,
          lowestFee: null,
          customerId: null,
          chargeTypes: [],
          validDateRange: [],
          validDateStart: null,
          validDateEnd: null
        },

        rules: {
          warehouseIds: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          userGroupIds: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          chargeTypes: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          numStr: [{
            required: true,
            message: '请输入',
            trigger: 'blur'
          }],
          payNameId: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          amoebaSubjectId: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          settlementUserId: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          priceStr: [{
            required: true,
            message: '请输入',
            trigger: 'blur'
          }],
          currency: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }]
        },

        compareOptions: [
        {
          value: '=',
          label: '='
        }, {
          value: '≠',
          label: '≠'
        }, {
          value: '>',
          label: '>'
        }, {
          value: '<',
          label: '<'
        }, {
          value: '包含',
          label: '包含'
        }],

        chargeTypeOptions: [
          {
            value: '1',
            label: '对外应收'
          }, {
            value: '2',
            label: '阿米巴应收'
          }]
      };
    },

    mounted() {
      this.init();
      if (this.$store.state.edit.id) {
        this.editData();
      } else {
        //新增时显示一行空的触发条件输入框
        let obj = {};
        obj.expressionList = [];
        obj.expressionList.push({
          variableCodeId: null,
          compareFlag: '=',
          compareValue: ''
        });
        this.triggerConditions.push(obj);
      }
    },
    methods: {
      /**
       * 查询客户
       * */
      async searchCustomer(query) {
        if (query !== "" && query.length > 1) {
          let res = await ajax("searchCustomer", {
            arg: query
          });
          this.customerMap = res.data;
        }
      },

      /**
       * 查询排除的客户
       * */
      async searchExcludeCustomer(query) {
        if (query !== "" && query.length > 1) {
          let res = await ajax("searchCustomer", {
            arg: query
          });
          this.excludeCustomerMap = res.data;
        }
      },

      addTriggerCondition() {
        let obj = {};
        obj.expressionList = [];
        obj.expressionList.push({
          variableCodeId: null,
          compareFlag: '=',
          compareValue: ''
        });
        this.triggerConditions.push(obj);
      },

      removeTriggerCondition() {
        let length = this.triggerConditions.length;
        this.triggerConditions.splice(length-1, 1);
      },

      addLine(index) {
        this.triggerConditions[index].expressionList.push({
          variableCodeId: null,
          compareFlag: '=',
          compareValue: ''
        });
      },

      removeLine(index, subIndex) {
        this.triggerConditions[index].expressionList.splice(subIndex, 1);
      },

      //初始化下拉框选项
      async init() {
        const { code, data, message } = await ajax(
          "getInitData",
          {}
        );
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          return;
        }
        this.initData = data;
      },

      cancel() {
        closeDialog();
      },

      selectAll() {
        let warehouseIdArr = Object.keys(this.initData.warehouseMap);
        this.formData.warehouseIds = [];
        for (let id of warehouseIdArr) {
          this.formData.warehouseIds.push(parseInt(id));
        }
      },

      /**
       * 客服部
       * */
      selectAllCustomerServiceDept() {
        let allServiceDeptIdArr = Object.keys(this.initData.allServiceDeptMap);
        this.formData.deptIds = [];
        for (let id of allServiceDeptIdArr) {
          this.formData.deptIds.push(parseInt(id));
        }
      },

      /**
       * 销售部
       * */
      selectAllSaleDept() {
        let allSaleDeptIdArr = Object.keys(this.initData.allSaleDeptMap);
        this.formData.deptIds = [];
        for (let id of allSaleDeptIdArr) {
          this.formData.deptIds.push(parseInt(id));
        }
      },

      /**
       * 客服及销售部
       * */
      selectAllServiceAndSaleDept() {
        let allServiceDeptIdArr = Object.keys(this.initData.allServiceDeptMap);
        let allSaleDeptIdArr = Object.keys(this.initData.allSaleDeptMap);
        this.formData.deptIds = [];
        for (let id of allServiceDeptIdArr) {
          this.formData.deptIds.push(parseInt(id));
        }
        for (let id of allSaleDeptIdArr) {
          this.formData.deptIds.push(parseInt(id));
        }
      },

      /**
       * 全选
       * */
      selectAllDept() {
        let deptIdArr = Object.keys(this.initData.deptMap);
        this.formData.deptIds = [];
        for (let id of deptIdArr) {
          this.formData.deptIds.push(parseInt(id));
        }
      },

      clearAllDept() {
        this.formData.deptIds = [];
      },

      /**
       * 数据回显
       * */
      async editData() {
        const res = await ajax("findById",
          {id: this.$store.state.edit.id}
        );
        if (res.code !== 200) {
          if (res.message) {
            this.$message.error(res.message);
          } else {
            this.$message.error("服务器异常");
          }
        } else {
          this.formData = res.data;
          //回显触发条件
          this.triggerConditions = res.data.triggerConditions;
          //回显有效时间
          this.formData.validDateRange = [];
          let validDateStart = this.formData.validDateStart;
          let validDateEnd = this.formData.validDateEnd;
          if (validDateStart) {
            this.formData.validDateRange.push(validDateStart);
          }
          if (validDateEnd) {
            this.formData.validDateRange.push(validDateEnd);
          }
          //客户简称
          let selectedCustomerArr = res.data2;
          if (selectedCustomerArr != null) {
            for (let item of selectedCustomerArr) {
              this.customerMap[item.id] = item.customerNameShort;
            }
          }
          //排除的客户
          let excludeCustomerArr = res.data3;
          if (excludeCustomerArr != null) {
            for (let item of excludeCustomerArr) {
              this.excludeCustomerMap[item.id] = item.customerNameShort;
            }
          }
        }
      },

      //数据校验
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.save();
          } else {
            console.log("数据校验失败，不允许提交");
            return false;
          }
        });
      },

      async save() {
        //客户简称、渠道类型、入库渠道三者必须有一个有值
        let customerChannelIds = this.formData.customerChannelIds;
        let channelTypeId = this.formData.channelTypeId;
        let customerId = this.formData.customerId;
        if (customerChannelIds.length == 0 && channelTypeId == null && customerId == null) {
          this.$message.error("客户简称、渠道类型、入库渠道至少要选一项");
          return;
        }
        //校验触发条件
        let triggerConditions = this.triggerConditions;
        for (let item of triggerConditions) {
          for (let obj of item.expressionList) {
            if (!obj.variableCodeId || !obj.compareValue) {
              this.$message.error("触发条件请填写完整");
              return;
            }
          }
        }
        this.formData.triggerConditions = triggerConditions;
        //校验有效时间
        let validDateRange = this.formData.validDateRange;
        if (validDateRange) {
          if (validDateRange.length == 1) {
            this.$message.error("有效时间请填写完整");
            return;
          }
          this.formData.validDateStart = validDateRange[0];
          this.formData.validDateEnd = validDateRange[1];
        }
        //请求后台
        const { code, data, message } = await ajax(
          "save",
          this.formData
        );
        if (code === 200) {
          this.$message({
            type: "success",
            message: "保存成功！"
          });
          closeDialog();
        } else {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
        }
      },

      //选择费用名称，默认选中对应的阿米巴科目
      changeSelect(val) {
        let payNameArr = this.initData.payNameList;
        for (let item of payNameArr) {
          if (item.id == val) {
            this.formData.amoebaSubjectId = item.amoebaSubjectId;
            break;
          }
        }
      }
    }
  };
</script>


<style>

</style>
